﻿using System;
using System.Data;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Oms.Model.Repositories;
using Oms.DomainModel;
using System.Linq.Expressions;

namespace Oms.Infrastructure.Repositories
{
    public class EntityRepository<E> : IRepository<E> where E: class
    {
        protected DbSet<E> DbSet;
        protected DbContext dataContext;
        
        public EntityRepository(DbContext dataContext)
        {
            DbSet = dataContext.Set<E>();
            this.dataContext = dataContext;
            
        }

        public void Create(E entity)
        {
            DbSet.Add(entity);
        }

        public void Update(E entity) 
        {
            dataContext.Entry(entity).State = EntityState.Modified;
            dataContext.SaveChanges();
        }
 
        public void Delete(E entity)
        {
            DbSet.Remove(entity);
        }
 
        public IQueryable<E> GetByFilter(Expression<Func<E, bool>> filter)
        {
            return DbSet.Where(filter);
        }
 
        public IQueryable<E> GetAll()
        {
            return DbSet;
        }
 
        public E GetById(long id)
        {
            return DbSet.Find(id);
        }
    }
}
